package com.ali.ttt.netty.client.config;

import com.ali.ttt.netty.common.config.NettyServerProperties;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoop;
import io.netty.util.concurrent.GenericFutureListener;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

/**
 * @author yuxl
 */
@Slf4j
@Configuration
@ConditionalOnProperty(name = "netty.client.enable", havingValue = "true")
public class ClientStarter {

    @Resource
    private NettyClient nettyClient;

    @Resource
    private NettyServerProperties nettyServerProperties;

    private String host = nettyServerProperties.getHost();
    private int port = nettyServerProperties.getProd();
    private Channel channel;

    private GenericFutureListener<ChannelFuture> closeListener = (ChannelFuture f) ->
    {
        log.info("连接已经断开……");
        channel = f.channel();
    };

    private GenericFutureListener<ChannelFuture> connectedListener= (ChannelFuture f) ->
    {
        final EventLoop eventLoop = f.channel().eventLoop();
        if (f.isSuccess()){
            log.info("\n----------------------------------------------------------\n\t" +
                            "netty客户端 连接成功\n\t" +
                            "External: \t\033[1;34m{}:{}\033[0m\n\t" +
                            "----------------------------------------------------------",
                    host,
                    port
            );
            channel = f.channel();
            channel.closeFuture().addListener(closeListener);
        } else {
            log.info("连接失败! ");
        }
    };



    @PostConstruct
    public void run(){
        nettyClient.setHost(host);
        nettyClient.setPort(port);
        nettyClient.doConnect();
    }
}
